/*
 * Copyright (C) 2017 Anadea Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.anadeainc.rxbus.demo.slice;

import com.anadeainc.rxbus.Bus;
import com.anadeainc.rxbus.BusProvider;
import com.anadeainc.rxbus.CustomSubscriber;
import com.anadeainc.rxbus.Subscribe;
import com.anadeainc.rxbus.demo.ResourceTable;
import com.anadeainc.rxbus.demo.SomeEvent;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;

import java.util.logging.Logger;

public class MainAbilitySlice extends AbilitySlice {
    Bus bus;
    private static final String TAG = "RxBus";
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        bus = BusProvider.getInstance();
        Button button = (Button) findComponentById(ResourceTable.Id_button);
        button.setClickedListener(component -> bus.post(new SomeEvent("Specific message")));
        CustomSubscriber<SomeEvent> customSubscriber = bus.obtainSubscriber(SomeEvent.class,
                new Consumer<SomeEvent>() {
                    @Override
                    public void accept(SomeEvent someEvent) throws Throwable {
                        Logger.getLogger(TAG).info("自定义消费者收到事件:" + someEvent.message);
                    }
                })
                .withFilter(new io.reactivex.rxjava3.functions.Predicate<SomeEvent>() {
                    @Override
                    public boolean test(SomeEvent someEvent) throws Throwable {
                        return "Specific message".equals(someEvent.message);
                    }
                })
                .withScheduler(Schedulers.trampoline());

        bus.register(this);
        bus.registerSubscriber(this, customSubscriber);
    }

    @Subscribe
    public void onEvent(SomeEvent event) {
        Logger.getLogger(TAG).info("注解消费者收到事件:" + event.message);
    }

    @Override
    protected void onStop() {
        super.onStop();
        bus.unregister(this);
    }
}
